package com.office.web;

import com.office.bean.*;
import com.office.service.DepartService;
import com.office.service.EmpService;
import com.office.service.LoginLogService;
import com.office.utils.Md5Util;
import com.office.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
public class EmpController {
    @Autowired
    EmpService empService;

    @Autowired
    LoginLogService loginLogService;

    @Autowired
    DepartService departService;

    @Autowired
    Md5Pass md5Pass;

    @RequestMapping({"/login","/"})
    public String login(){

        return "login";
    }

    @RequestMapping("/emp_login")
    public void login(Emp emp,String ip,String city, HttpServletResponse response, HttpSession session) throws Exception {
        response.setContentType("text/html;charset=utf-8");

        String pass = emp.getPass();
        String newPass = md5Pass.getSalt1()+pass+md5Pass.getSalt2();
        String s = Md5Util.encodeByMd5(newPass);
       
        emp.setPass(s);
        Emp loginUser = empService.login(emp);
        if (loginUser != null) {
            if (loginUser.getFlag()==1){
                session.setAttribute("loginUser",loginUser);
                LoginLog loginLog = new LoginLog(ip,loginUser.getNo(),city);
                loginLogService.addLoginLog(loginLog);
                response.getWriter().write("<script>location.href='/index';</script>");
            }else {
                response.getWriter().write("<script>alert('账号已被禁用,请联系管理员!');location.href='/';</script>");
            }
            //存值当前用户登录状态

        } else {
            response.getWriter().write("<script>alert('账号或密码错误!');location.href='/';</script>");
        }
    }

    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "login";
    }

    @RequestMapping("/addLog")
    @ResponseBody
    public List<LoginLog> addlog(HttpSession session){
        Emp loginUser = (Emp) session.getAttribute("loginUser");

        return loginLogService.findLoginLogs(loginUser.getNo());
    }
    @RequestMapping("/findDepart")
    @ResponseBody
    public List<Depart> findDepart(){
        return departService.findDepart();
    }

    @RequestMapping("/emp_list")

    public String list(long pageIndex, long pageSize, Model model){
        //总条数

        long totalcount = empService.findTotalcount();
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("pageStart",(pageIndex-1)*pageSize);
        map.put("pageSize",pageSize);
        //每页的数据
        List<Emp> emps = empService.findEmpsByPage(map);
        //分页数据封装工具类
        PageUtils<Emp> pageUtils=new PageUtils<Emp>(pageIndex,pageSize,totalcount,emps);
        model.addAttribute("pageUtils",pageUtils);
        //列表页面
        return "emplist";
    }

    @RequestMapping("/emp_add")
    public void add(Emp emp, HttpServletResponse response) throws Exception{
        //设置浏览器的响应内容
        String newPass = md5Pass.getSalt1()+md5Pass.getPass()+md5Pass.getSalt2();
        String s = Md5Util.encodeByMd5(newPass);
        emp.setPass(s);
        response.setContentType("text/html;charset=utf-8");
        int count = empService.addEmp(emp);
        if(count>0){
            response.getWriter().write("<script>alert('新增员工成功');location.href='/emp_list?pageIndex=1&pageSize=5';</script>");
        }else{
            response.getWriter().write("<script>alert('新增员工失败');location.href='/html_empadd';</script>");
        }
    }


    /**
     * 上传文件
     * @param file
     * @param session
     * @return
     */
    @RequestMapping("/emp_photoupload")
    @ResponseBody
    public Message photoupload(MultipartFile file,HttpSession session){
        Message result = new Message();

        try {
            String originalFilename = file.getOriginalFilename();
            System.out.println("源文件名"+originalFilename);
            String hou = originalFilename.split("\\.")[1];
            String  uuid = UUID.randomUUID().toString();
            String newFile = uuid+"."+hou;
            System.out.println("新文件名"+newFile);
            String resultPath = session.getServletContext().getRealPath("/media/images")+"/"+newFile;
            file.transferTo(new File(resultPath));
            System.out.println("上传成功");

            result.setCode(1000);

            result.setMsg(newFile);
        } catch (IOException e) {
            result.setCode(5000);
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("/update_pass")
    public void updatePass(Emp emp,String pass1,HttpSession session, HttpServletResponse response) throws Exception{
        response.setContentType("text/html;charset=utf-8");
        Emp loginUser = (Emp)session.getAttribute("loginUser");
        String oldPass = emp.getPass();
        String md5OldPass = md5Pass.getSalt1()+oldPass+md5Pass.getSalt2();
        String md5NewPass = Md5Util.encodeByMd5(md5OldPass);
        if (md5NewPass.equals(loginUser.getPass())){
            String md5OldPass1 = md5Pass.getSalt1()+pass1+md5Pass.getSalt2();
            String md5NewPass1 = Md5Util.encodeByMd5(md5OldPass1);
            loginUser.setPass(md5NewPass1);
            int i = empService.updatePass(loginUser);
            if (i>0){
                response.getWriter().write("<script>alert('修改密码成功');parent.location.href='/index';</script>");
            }else {
                response.getWriter().write("<script>alert('修改密码失败');location.href='/html_password';</script>");
            }
        }else {
            response.getWriter().write("<script>alert('原密码错误');location.href='/html_password';</script>");
        }
    }

    @RequestMapping("/update_photo")
    public void update_photo(MultipartFile file,HttpSession session,HttpServletResponse response)  {
        response.setContentType("text/html;charset=utf-8");
        Emp loginUser = (Emp)session.getAttribute("loginUser");
        String oldPhotoName = loginUser.getPhoto();

        //上传文件
        try {
            String originalFilename = file.getOriginalFilename();
            String hou = originalFilename.split("\\.")[1];
            String  uuid = UUID.randomUUID().toString();
            String newFile = uuid+"."+hou;
            String resultPath = session.getServletContext().getRealPath("/media/images")+"/"+newFile;
            file.transferTo(new File(resultPath));
            //删除旧图片
            String oldPath = session.getServletContext().getRealPath("/media/images")+"/"+oldPhotoName;
            File oldFile = new File(oldPath);
            if (oldFile.exists()){
                oldFile.delete();
            }
            //session添加新图片
            loginUser.setPhoto(newFile);
            int i = empService.updatePhoto(loginUser);
            if (i>0){
                response.getWriter().write("<script>alert('头像修改成功');parent.location.href='/html_index';</script>");
            }else {
                response.getWriter().write("<script>alert('头像修改失败');location.href='/update_photo';</script>");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/delete_emp")
    @ResponseBody
    public boolean delete_emp(int id){
        return empService.deleteEmpById(id);
    }


    @RequestMapping("/update_toemp/{id}")
    public String update_toemp(@PathVariable("id") int id,Model model){
        Emp updateEmp = empService.findEmp(id);
        model.addAttribute("updateEmp",updateEmp);
        return "empupdate";
    }

    @RequestMapping("/update_emp")
    public void update_emp(Emp emp,HttpServletResponse response) throws Exception{
        response.setContentType("text/html;charset=utf-8");
        int update = empService.update(emp);
        if (update>0){
            response.getWriter().write("<script>alert('员工修改成功');location.href='/emp_list?pageIndex=1&pageSize=5';</script>");
        }else {
            response.getWriter().write("<script>alert('员工修改失败');location.href='/update_toemp/{"+emp.getId()+"}';</script>");
        }
    }

    @RequestMapping("/findDepart1")
    @ResponseBody
    public List<Depart> findDepart1(){
        return departService.findDepart();
    }

    @RequestMapping("/emp_updateFlag")
    @ResponseBody
    public boolean emp_updateFlag(int id,int flag){
        return empService.updateFlag(id,flag);
    }

}
